<?php
/**
 * Created by PhpStorm.
 * User: trisatria
 * Date: 1/6/14
 * Time: 1:17 PM
 */
namespace Frontend\Controller;
use Admin\Form\AdminTopicForm;
use Zend\Authentication\AuthenticationService;
use Zend\Mvc\Controller\AbstractActionController;
use Zend\Stdlib\ArrayObject;
use Zend\View\Model\ViewModel;
use Velacolib\Utility\Utility;
use Admin\Model\AdminTopicTable;
use Admin\Model\AdminTopic;
use Admin\Model\AdminTopicImg;
use Admin\Model\AdminCommend;
use Frontend\Helper\SimpleImage;
use Admin\Model\AdminUser;
use Admin\Model\AdminUserTable;
use Zend\Session\Container;
use Zend\View\View;
use Frontend\Helper\MobileDetect;
use Frontend\Helper\JpegFit;

class RaovatController extends AbstractActionController
{
    protected  $auth;
    protected  $topicModel;
    protected $topicImg;
    protected $commentModel;
    protected $userContactTable;
    protected $userModel;
    protected $translator;
    protected $mobileDetect;
    protected $isPhone;
    protected $isTablet;


    public function onDispatch(\Zend\Mvc\MvcEvent $e)
    {
        //Utility::CheckLogin($this,'/user/login');

        $this->topicModel = Utility::UserGateway('Admin\Model\AdminTopicTable');
        $this->commentModel = Utility::UserGateway('Admin\Model\AdminCommendTable');
        $this->topicImg = Utility::UserGateway('Admin\Model\AdminTopicImgTable');
        $this->userContactTable = Utility::UserGateway('Admin\Model\AdminUserContactTable');
        $this->userModel = Utility::UserGateway('Admin\Model\AdminUserTable');
        $this->translator = Utility::translate();
        $mobileDetect = new MobileDetect();
        $this->isPhone = $mobileDetect->isMobile();
        $this->isTablet  = $mobileDetect->isTablet();

        $this->layout('frontend/layout');
        $user_session = new Container('user');
        $user_session->username = 'Hung';
        return parent::onDispatch($e);
    }

    public function init(){
        //$this->Acl->SetModule('Project');
        //if(!$this->Acl->Check())
        //  $this->redirect()->toRoute('home', array ('action' => 'index'));
    }

    public function indexAction()
    {
        echo 'index';
    }
    public function dangtinAction(){

        $response = array();
        $response['redirect'] = false;
        $Auth_service = new AuthenticationService();
        $auth = $Auth_service->getIdentity();
        $topic_id = '';
        $user_name = '';

        $request = $this->getRequest();

        if($request->isPost()){

            //start add topic
            $topic = new AdminTopic();
            $data = $this->params()->fromPost();

            if(isset($data['gel'])){
                $gellary = $data['gel'];
                $data['images'] = $data['gel'][0];
                $data['thumb'] = str_replace("/img/upload/",'/img/upload/thumb/',$data['images']);
            }else{
                $data['images'] = '/img/upload/no_photo_avalable.jpg';
                $data['thumb'] = '/img/upload/no_photo_avalable.jpg';
            }

            if( !isset($data['gel']) && $data['topic_type'] ==0){
                $response['result']  = false;
                $response['message']  = $this->translator->translate('You have not selected topic image');

                return new ViewModel(array(
                    'response' =>$response
                ));
            }
            $full_desc =  strip_tags($data['full_description'],'<a>');

            $data['full_description'] =  htmlentities($full_desc);
            $data['status'] = 2;
            $data['create_date'] = date("Y-m-d H:i:s");
            $data['up_date'] = time();
            $data['expire_date']  = date("Y-m-d",time()+2592000);
            $data['slug'] = Utility::alphabetconvert($data['title']).'-'.time();
            $data['is_public'] = 'yes';
            unset($data['next']);
            // kiem tra user co dang nhap chua, neu ko co dang nhap thi dien thong tin de dang ky
            if($Auth_service->hasIdentity() ==1){
                $data['user_id'] = $auth->userid;
                // exchange array->object
                $topic->exchangeArray($data);
                $topic_id = $this->topicModel->saveTopic($topic);
                //end add topic

                //add hinh vao table topic_img
                if(isset($gellary))
                {
                    foreach($gellary as $g){

                        $data_gallery = array(
                            'topic_id' => $topic_id,
                            'link' =>  str_replace("/img/upload/","/img/upload/",$g),
                            'user_id' => $data['user_id']
                        );
                        $topicImgModel = new AdminTopicImg();
                        $topicImgModel->exchangeArray($data_gallery);
                        $this->topicImg->saveTopicImg($topicImgModel);

                    }
                }

                $response['result'] = true;
                $response['message'] = $this->translator->translate('Create post success');
                $response['redirect'] = true;
                $url = '/raovat/cleared/'.$data['slug'].'/'.$topic_id;
                $this->redirect()->toUrl($url);

            }else{
                    setcookie('data_step1', '', time()-(3600) , '/');
                    $cookie_data = json_encode($data);
                    //set cookie expires after a week
                    setcookie('data_step1', $cookie_data, time()+(3600) , '/');
                $data_step1 = json_decode($cookie_data);
                    $this->redirect()->toUrl('/raovat/dangtin-buoc2');
            }
        }


    }


    public function dangtinBuoc2Action(){
        $request = $this->getRequest();

        if($request->isPost()){
            $topic = new AdminTopic();
            $data_step2 = $this->params()->fromPost();

                if($data_step2['login'] == 'true'){
                    unset($data_step2['login']);

                    $user_table = Utility::UserGateway('Admin\Model\AdminUserTable');
                    $user_table->setLoginUser($data_step2);
                    $login_obj = new AuthenticationService(null, $user_table)   ;
                    $login_obj->authenticate();
                    $user_id = $login_obj->getIdentity()->userid ;
                    $data_step1 = json_decode($_COOKIE['data_step1']);
                    $data_step1->user_id = $user_id;
                    if(isset($data_step1->gel)){
                        $gellary = $data_step1->gel;
                    }

                    unset($data_step1->gel);
                    $array_data = array();
                    foreach($data_step1 as $key=>$val){
                        $array_data[$key] = $val;
                    }
                    // exchange array->object
                    $topic->exchangeArray($array_data);

                    $topic_id = $this->topicModel->saveTopic($topic);
                    if(isset($gellary))
                    {
                        foreach($gellary as $g){

                            $data_gallery = array(
                                'topic_id' => $topic_id,
                                'link' =>  str_replace("/img/upload/","/img/upload/",$g),
                                'user_id' => $user_id
                            );
                            $topicImgModel = new AdminTopicImg();
                            $topicImgModel->exchangeArray($data_gallery);
                            $this->topicImg->saveTopicImg($topicImgModel);

                        }
                    }
                    $url = '/raovat/cleared/'.$data_step1->slug.'/'.$topic_id;

                    $this->redirect()->toUrl($url);


                }
            if(isset($data_step2['login']) && $data_step2['login'] =='false'){

                    unset($data_step2['login']);
                    if( !isset($_COOKIE['data_step1'] ) ) {
                        $response['result']  = false;
                        $response['message']  = 'Lỗi kết nối mạng, vui lòng kiểm tra lại kết nối mạng';
                                $template_path = 'frontend/raovat/dangtin.phtml';

                        $view = new ViewModel(array(
                            'response'=>$response
                        ));
                        $view->setTemplate($template_path);
                        return $view;

                    }

                   (int) $uid = $this->adduserAction($data_step2);
                    $data_step1 = json_decode($_COOKIE['data_step1']);
                    $data_step1->user_id = (int) $uid;

                    if(isset($data_step1->gel)){
                        $gellary = $data_step1->gel;
                    }
                    // exchange array->object
                    unset($data_step1->gel);
                        $array_data = array();
                        foreach($data_step1 as $key=>$val){
                            $array_data[$key] = $val;
                        }
                    $topic->exchangeArray($array_data);
                    $topic_id = $this->topicModel->saveTopic($topic);
                    if(isset($gellary))
                    {
                        foreach($gellary as $g){

                            $data_gallery = array(
                                'topic_id' => $topic_id,
                                'link' =>  str_replace("/img/upload/","/img/upload/",$g),
                                'user_id' => $uid
                            );
                            $topicImgModel = new AdminTopicImg();
                            $topicImgModel->exchangeArray($data_gallery);
                            $this->topicImg->saveTopicImg($topicImgModel);

                        }
                    }
                    $url = '/raovat/cleared/'.$data_step1->slug.'/'.$topic_id.'/'.$data_step2['email'];

                    $this->redirect()->toUrl($url);

                }
        }


    }

    function clearedAction(){
       $slug = $this->params()->fromRoute('slug');
        $email = $this->params()->fromRoute('username');
        if($slug != ''){
            $topic = $this->topicModel->getTopicByslug($slug);
            return new ViewModel(array(
                'topic' => $topic,
                'email' =>$email
            ));

        }

    }

    function editAction(){
        $result = false;
        $this->auth = Utility::CheckLogin($this,'/user/login');
        $topic_slug = $this->params()->fromRoute('slug',0);
        $topic_id = $this->params()->fromRoute('id',0);
        $auth = new AuthenticationService();
        $auth_id = $auth->getIdentity()->userid;

        $topic_model = new AdminTopic();
        $topic = $this->topicModel->getTopicByslug($topic_slug);
        $topic_gellary = $this->topicImg->getTopicImgByTopic($topic_id);
        $gallery_hidden = $this->topicImg->getTopicImgByTopic($topic_id);
        $request = $this->getRequest();
        if($request->isPost()){
            //start add topic
            $topic = new AdminTopic();
            $data = $this->params()->fromPost();
            if(isset($data['gel'])){
            $gellary = $data['gel'];
            $data['images'] = $gellary[0];
            unset($data['gel']);
            $data['status'] = 1;
            $data['thumb'] = $data['images'];
            }
            $data['price'] = trim($data['price']);
            $data['id'] = $topic_id;
            $data['user_id'] = $auth_id;
            $data['status'] = 2;
            $data['expire_date']  = date("Y-m-d",time()+2592000);
            $data['slug'] = Utility::alphabetconvert($data['title']).'-'.time();
            $topic->exchangeArray($data);
            $topic_id = $this->topicModel->saveTopic($topic);
            //end add topic

            //start add gallery
            $this->topicImg->deleteTopicImgByTopic($topic_id);
            if(isset($gellary)){
                foreach($gellary as $g){
                    $data_gallery = array(
                        'topic_id' => $topic_id,
                        'link' => $g,
                        'user_id' => $this->auth->userid
                    );
                    $topicImgModel = new AdminTopicImg();
                    $topicImgModel->exchangeArray($data_gallery);
                    $tof = $this->topicImg->saveTopicImg($topicImgModel);
                }
            }
            //end add gallery
            $topic_gellary = $this->topicImg->getTopicImgByTopic($topic_id);
            $gallery_hidden = $this->topicImg->getTopicImgByTopic($topic_id);
            $topic = $this->topicModel->getTopic($topic_id);
            $result = true;
            return new ViewModel(array(
                'topic' => $topic,
                'topic_gellary'=>$topic_gellary,
                'gallery_hidden'  =>$gallery_hidden   ,
                'result'=>$result
            ));
        }


        return new ViewModel(array(
            'topic' => $topic,
            'auth'=>$this->auth,
            'topic_gellary'=>$topic_gellary,
            'gallery_hidden'  =>$gallery_hidden   ,
            'result'=>$result
        ));

    }

    public function chitietAction(){

        $topic_slug = $this->params()->fromRoute('slug',0);
        $topic_id = $this->params()->fromRoute('id',0);
        $view_product = array();
        if($this->isPhone || $this->isTablet){
            $arrTopic = $this->topicModel->getTopicJoinBySlug($topic_slug);

            $image_topic = $this->topicImg->getTopicImgByTopic($topic_id);

            $user_contact = $this->userContactTable->getUserContact($arrTopic->user_id);
            return new ViewModel(array(
                'topics' => $arrTopic,
                'image'=>$image_topic,
                'userContact' => $user_contact
            ));
        }else{
            $arrTopic = $this->topicModel->getTopicJoinBySlug($topic_slug);
            if($arrTopic == null){
                $this->getResponse()->setStatusCode(404);
                $viewModel = new ViewModel();
                $viewModel->setTerminal(true);
                return $viewModel;
            }
            $image_topic = $this->topicImg->getTopicImgByTopic($topic_id);
            $user_contact = $this->userContactTable->getUserContact($arrTopic->user_id);
            //$ip = Utility::get_client_ip();
            // set cookie product viewed
            if(isset($_COOKIE['topic_id']))
            {
                $topic_id_array = json_decode($_COOKIE['topic_id']);

                if(is_array($topic_id_array)){
                    if(!in_array($topic_id, $topic_id_array,true) ){
                        $view = ((int) $arrTopic->viewed) +1;
                        $this->topicModel->viewtopic($view,$topic_id);
                    }
                }
                //decode cookie string from JSON
                $cookieArr = (array) json_decode($_COOKIE['topic_id']);

                //push additional data
                array_push($cookieArr, $topic_id);

                //remove empty values
                foreach($cookieArr as $k => $v){ if($v == '' || is_null($v) || $v == 0){ unset($cookieArr[$k]); } }

                //encode data again for cookie
                $cookie_data = json_encode($cookieArr);

                //need to limit cookie size. Default is set to 4Kb. If it is greater than limit. it then gets reset.
                $cookie_data = mb_strlen($cookie_data) >= 4096 ? '' : $cookie_data;

                //destroy cookie
                setcookie('topic_id', '', time()-3600 , '/');

                //set cookie with new data and expires after a week
                setcookie('topic_id', $cookie_data, time()+(3600) , '/');

            }else{
                //create cookie with json string etc.
                $cookie_data = json_encode($topic_id);
                //set cookie expires after a week
                setcookie('topic_id', $cookie_data, time()+(3600) , '/');

            }

            if(isset($_COOKIE['topic_id'])){
                $view_product = $this->topicModel->viewed_products(json_decode($_COOKIE['topic_id']));
            } else{
                $view_product = false;
            }

            $related_query = array(
                'topic_type' => $arrTopic->topic_type,
                'cat_id' => $arrTopic->cat_id,
                'topic_location' => $arrTopic->topic_location,
                'topic_type' => $arrTopic->topic_type  ,
                'status'=>1
            );
            $related_products = $this->topicModel->RelatedProduct($related_query);
            $related_products->setItemCountPerPage(10);

            return new ViewModel(array(
                'topics' => $arrTopic,
                'image'=>$image_topic,
                'userContact' => $user_contact,
                'related_products' => $related_products ,
                'viewed_products'=>$view_product
            ));
        }

    }


    /**
     * @param int $limit
     */
    public function fetchAction($limit = 21){

        $auth = new AuthenticationService();

        $userid = $auth->getIdentity()->userid;
        // $limit = $_REQUEST['start'];
        $data = $this->topicModel->fetchTopicIndex($userid,0,$limit,20);
        // header("ContentType : application/json");
        // echo '<pre>';
        // echo json_encode($data);die;

        $data_topic = $this->topicModel->fetchTopicIndex($userid,0,1000);

        $total = count($data_topic);

        // How many items to list per page
        $limit = 10;
        // How many pages will there be
        $pages = ceil($total / $limit);

        //current page
        $page =  $_POST['page'];    //$this->params()->fromQuery('page');



        // Calculate the offset for the query
        $offset = ($page - 1)  * $limit;
        // Some information to display to the user
        $start = $offset;
        $end = min(($offset + $limit), $total);

        if($page < $pages){
            $data_topic = $this->topicModel->fetchTopicIndex($userid,$start,$end);
            header("ContentType : application/json");
            echo json_encode($data_topic);

        }

        die;
    }

    /*
     * fetch topic for new user
     *  */
    public function fetchfornewuserAction(){

        $auth = new AuthenticationService();
        //$userid = $auth->getIdentity()->userid;
        $data_topic_count = $this->topicModel->fetch_topic_for_new_user();
        $total = count($data_topic_count);
        // How many items to list per page
        $limit = ITEM_PER_PAGE;
        // How many pages will there be
        $pages = ceil($total / $limit);
        //current page
        $page =  $this->params()->fromQuery('page');    //$this->params()->fromQuery('page');
        // Calculate the offset for the query
        $offset = ($page - 1)  * $limit;
        // Some information to display to the user
        $start = $offset + 1;

        $end = min(($offset + $limit), $total);

        if($page <= $pages){
            $data_topic = $this->topicModel->fetch_topic_for_new_user($start,$end);
            //header("ContentType : application/json");
            //echo json_encode($data_topic);
            $view = new ViewModel(array('data'=>$data_topic));
            $view->setTerminal(true);
            return $view;

        }
        $view = new ViewModel(array('data'=>''));
        $view->setTerminal(true);
        return $view;
        //die;
    }


    public function loadnewAction(){

        $data_topic = $this->topicModel->fetch_new_topic();
        header("ContentType : application/json");
        echo json_encode($data_topic);


        die;
    }


    //topic - img
    public function AddTopicImgAction(){

        $this->auth = Utility::CheckLogin($this,'/user/login');
        $file = $this->params()->fromFiles();
        $post = $this->params()->fromPost();

        $file_name = $file['file']['name'];
        $file_tmp = $file['file']['tmp_name'];
        $file_size = $file['file']['size'];
        $file_error = $file['file']['error'];
        $file_type = $file['file']['type'];
        $new_name = time().$file_name;
        //move_uploaded_file($file_tmp, "./public/img/upload/".$new_name);


            $simpleImage = new SimpleImage($file_tmp);
            $img_width = $simpleImage->getWidth();
            $img_height = $simpleImage->getHeight();
            if($img_width > 1368){
                $simpleImage->resizeToWidth(1368);
                $simpleImage->save("./public/img/upload/".$new_name);

            }else{
                $simpleImage->save("./public/img/upload/".$new_name);
            }
            sleep(1);
            $name_compess =  time().$file_name;
            $utility = new Utility();
            $utility->compress_image("./public/img/upload/".$new_name, "./public/img/upload/".$name_compess, 40);
            //fit image file

            $simpleImage = new SimpleImage("./public/img/upload/".$name_compess);
            $img_width = $simpleImage->getWidth();
            $img_height = $simpleImage->getHeight();

            $simpleImage->resizeToWidth(280);
            $simpleImage->save("./public/img/upload/thumb/".$name_compess);


        echo URL_IMAGE.$name_compess;
        die;

    }



    public function topicexpireAction(){
        $return = array();
      $return['sql'] =   $this->topicModel->del_topic_expire();
        $view = new ViewModel();
        $view->setTerminal(true);
        $return['view'] = $view;
        print_r($return);
        die;
    }

    /****
     * lay bai viet cua user
     * post user id
     * return array();
     **/
    public function getTopicOfUserAction(){
        $request = $this->getRequest();
        if($request->isPost()){
            $userid = $this->params()->fromPost('data');
          $result =  $this->topicModel->getTopicOfUser($userid,10);
            echo json_encode($result);die;
        }
    }

    /*
     *create phone image from phone number
     *get phone number from user_id
     */

    public function creImagePhoneAction(){

        $im = imagecreate(150, 30);
        $user_id = $_POST['id'];
        $user_info = $this->userModel->getUser($user_id);
        $bg = imagecolorallocate($im, 255, 255, 255);
        $text_color = imagecolorallocate($im, 0, 0, 0);
        imagestring($im, 7, 20, 9, $user_info->phone , $text_color);

// Set the content type header - in this case image/jpeg
        header('Content-Type: image/jpeg');
        $name = 'phone_'.time().'.png';
// Output the image
        imagepng($im,$_SERVER['DOCUMENT_ROOT'].'/img/phone/'.$name);

// Free up memory
        imagedestroy($im);
        echo $name;
        die;
    }

    function typeaheadAction(){
        $json_array = array();
       $typeahead = $this->topicModel->typeahead();
       foreach($typeahead as $type){
          $json_array[] = $type;
       }
        echo json_encode($json_array);die;
    }


    function typeaheadUserTopicAction(){
        $auth = new AuthenticationService();
        $user_id = $auth->getIdentity()->userid;
        $json_array = array();
        $typeahead = $this->topicModel->typeaheadUser($user_id);
        foreach($typeahead as $type){
            $json_array[] = $type;
        }
        echo json_encode($json_array);die;
    }



    function adduserAction($userinfo = array()){

        $user_id = 0;
        $user_model = new AdminUser();

        $userinfo['name'] = $userinfo['name'];

        $userinfo['status'] = '1';

        $userinfo['user_type'] = '2';

        $time = time();

        $userinfo['time_reg'] = $time;
        $password = $time;
        $userinfo['avatar'] = '/img/upload/user_temp/person-avatar.png';

        if(! isset($userinfo['password'])){
            $userinfo['password'] = md5($userinfo['email'] . $time);
        }else{
            $password = $userinfo['password'];
            $userinfo['password']  = md5($userinfo['email'].$userinfo['password'])   ;

        }


        // kiem tra trung email, neu trung thi email da su dung, yeu cau dang nhap
        // khong trung thi tu tao tai khoan cho khach hang
        $object = Utility::UserGateway('Admin\Model\AdminUserTable')->getUserByEmail($userinfo['email']);


        if (is_object($object)) {

            $user_id = false;
        } else {
            $user_model->exchangeArray($userinfo);
            $addUser = Utility::UserGateway('Admin\Model\AdminUserTable')->saveUser($user_model);

            $user_table = Utility::UserGateway('Admin\Model\AdminUserTable');
            $data['username'] = $userinfo['email'];
            $data['password'] =    $password;


            if ($addUser) {
                $user_id = $addUser;

                $user_table->setLoginUser($data);
                $login_obj = new AuthenticationService(null, $user_table)   ;
                $login_obj->authenticate();


                $response['result'] = true;
                $response['message'] = $this->translator->translate('Register success');
                $response['register'] = true;
                $response['user_id'] =   Utility::UserGateway('Admin\Model\AdminUserTable')->getLastIdInsert();

                //sending email verify to user register
                $smtp_option = null;
                $senderInfo = array(
                    'email' => 'mrhungmaster1905@gmail.com',
                    'name' => 'VelaCo'

                );

                $RecipientInfo = array(
                    'email' => $userinfo['email'],
                    'name' => $userinfo['name'],
                    'password'=>   $password
                );

                $template_path = 'admin/email/tpl/userregister';

                $subject = 'Xác nhận Tài khoản Minimall';

                Utility::SendMail(false, $smtp_option = null, $senderInfo, $RecipientInfo, $template_path, $subject);

            }
        }
        return $user_id;

    }
    function uptopicAction(){

        $topicid = $this->params()->fromPost('id');
        $topic = $this->topicModel->getTopic($topicid);
        $current_time = time();
        $time_elapsed = round($current_time - $topic->up_date);
        $hours = round($time_elapsed / 3600);
        if($hours>= 1){
            $topic->up_date = $current_time;
            $update = $this->topicModel->saveTopic($topic);
            if($topicid == $update){
                $response['result'] = true;
                $response['message'] = $this->translator->translate('Your article has renewed');
            }else{
                $response['result'] = false;
                $response['message'] = $this->translator->translate('Error');
            }
        } else{
            $response['result'] = false;
            $response['message'] = $this->translator->translate('Your article has renewed').'.'.$this->translator->translate('Remaining').' '.(round(60-($time_elapsed/60))).' ' .$this->translator->translate('minute');
        }

        echo json_encode($response);die;
    }

    function hiddenTopicAction(){

        $topicid = $this->params()->fromPost('id');
        $is_public = $this->params()->fromPost('is_public');
        $topic = $this->topicModel->getTopic($topicid);


            $topic->is_public = $is_public;
            $update = $this->topicModel->saveTopic($topic);
            if($update == $topicid){
                $response['result'] = true;
                $response['message'] = $this->translator->translate('Success');
            } else{
                $response['result'] = false;
                $response['message'] = $this->translator->translate('Error');
            }

        echo json_encode($response);die;
    }


    function emailToAuthorAction(){
        if($this->getRequest()->isPost()){
        $response['result'] = true;
        $data = $this->params()->fromPost();
        $senderInfo = array(
            'email' => $data['email'],
            'name' => $data['name']

        );
        $ip_address = Utility::get_client_ip();
        $data['client_ip'] = $ip_address;

        $RecipientInfo = array(
            'name'=>$data['recipient_name'],
            'email'=>$data['recipient_email'],
            'sender_email' => $data['email'],
            'sender_name' => $data['name'],
            'subject'=>$data['subject'],
            'content'=>$data['content']
        );

        $template_path = 'admin/email/tpl/emailcustomer';

        $subject = $data['subject'];

        Utility::SendMail(false, $smtp_option = null, $senderInfo, $RecipientInfo, $template_path, $subject);
        $response['message']     = $this->translator->translate('Send mail success!');
            echo json_encode($data);die;

        } else{
            $response['result'] = false;
            $response['message'] = $this->translator->translate('Method is not allowed');
        }
        echo json_encode($response);die;

    }
    public function validateEmailAction(){
        $request = $this->getRequest();
        if($request->isPost()){
            $post = $this->params()->fromPost();
            if($post['email'] == ''){
                $result['result'] = false;
                $result['message'] = 'Vui lòng nhập email';
                echo json_encode($result);   die;
            }
            if (!filter_var($post['email'], FILTER_VALIDATE_EMAIL)){
                $result['result'] = false;
                $result['message'] = 'Địa chỉ email không đúng';
                echo json_encode($result);   die;
            }
            $object = Utility::UserGateway('Admin\Model\AdminUserTable')->getUserByEmail($post['email']);
            if(is_object($object)){
                $result['result'] = false;
                $result['message'] = 'Email '.$post['email'].' đã có người sử dụng';
            } else{
                $result['result'] = true;
            }
            echo json_encode($result);   die;
        }

    }

}